package com.yuntsg.nnsfcp.util.EIHttpClient;

import com.alibaba.fastjson.JSONObject;
import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.util.httpclient.HttpClientConfig;
import com.yuntsg.nnsfcp.util.httpclient.HttpClientUtil;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

;

public class CssciHttpClient {

    public static String getHtml2(BasicCookieStore cookieStore, HttpClientConfig config) {
        System.out.println("当前的地址:" + config.getUrl());
        String html = null;
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse response;
            try {
                httpget = new HttpGet(config.getUrl());
                httpget.setConfig(config.getRequestConfig());
                httpget.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);

                if (!StringUtil.isEmpty(config.getRefer())) {
                    httpget.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httpget.addHeader(HttpHeaders.HOST, config.getHost());
                }
                response = httpClient.execute(httpget);
                int resStatu = response.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "--状态码" + resStatu);
                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(response);
                    if (html != null) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }


    public static Map getHtmlwithUrlDate(BasicCookieStore cookieStore, HttpClientConfig config) {
        System.out.println("当前的地址:" + config.getUrl());
        Map map = new HashMap();
        String html = "";
        String host = "https://www.engineeringvillage.com";
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().
                    setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse response;
            try {
                httpget = new HttpGet(config.getUrl());
                httpget.setConfig(config.getRequestConfig());
//                httpget.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
                httpget.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                //添加cookie 测试
//                httpget.addHeader("Cookie", "_vwo_uuid=DD461A38A4FA131B40B5FE7B865297644; __cfduid=da9c0002d4941a39a32db23a3e88a330f1548040635; _vis_opt_exp_3_combi=2; GUESTID=Guest_c77093b06d4a44e8b4218c7ba0a41877; _gcl_au=1.1.147275588.1548053682; com.silverpop.iMAWebCookie=742b0a97-d957-e288-8e82-6cb566d0b95c; __utma=39939830.973517206.1547703408.1548055030.1548055030.1; __utmz=39939830.1548055030.1.1.utmcsr=proquest.com|utmccn=(referral)|utmcmd=referral|utmcct=/APAC-CN/cn-products-services/; _vis_opt_s=3%7C; _vwo_uuid_v2=DD461A38A4FA131B40B5FE7B865297644|ff98be5550e653e38a3503d34a2d6d9a; _vwo_ds=3%3Aa_0%2Ct_0%3A0%241547703395%3A87.95916945%3A%3A%3A306_0%2C305_0%2C2_0; _ga=GA1.3.973517206.1547703408; _gid=GA1.3.872035860.1548053547; EBUQUSER=66b135fd72074b7dae74adabb686c90b; SERVERID=r6; EBSESSIONID=2af5155df9c1425cb92b1e08e0988183; JSESSIONID=zjun7ty397pvm4mt2buae96s; _ga=GA1.2.973517206.1547703408; _gid=GA1.2.872035860.1548053547; _gat_UA-69343401-3=1");
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httpget.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httpget.addHeader(HttpHeaders.HOST, config.getHost());
                }
                response = httpClient.execute(httpget);
                int resStatu = response.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "--状态码" + resStatu);
                if (resStatu == 301 || resStatu == 302) {
                    Header[] hs = response.getHeaders("Location");
                    String goUrl = "";
                    for (Header h : hs) {
                        map.put("gourl", h.getValue());
                        goUrl = host + h.getValue();
                        config.setUrl(goUrl);
                        System.out.println(h.getName() + "--" + h.getValue());
                    }
                }
                String htmlDate = getHtml(cookieStore, config);
                map.put("data", htmlDate);
                if (!htmlDate.equals("")) {
                    break;
                }
//                if (resStatu == HttpStatus.SC_OK) {
//                    html = HttpClientUtil.parsingHtml(response);
//                    if (html != null) {
//
//                    }
//                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return map;
    }


    /**
     * 通用的获取html的get方法
     */
    public static String getHtml(BasicCookieStore cookieStore, HttpClientConfig config) {
        System.out.println("当前的地址:" + config.getUrl());
        String html = null;
        for (int i = 1; i <= 3; i++) {
//            HttpHost httpHost = new HttpHost("58.56.149.198", 53281);
            CloseableHttpClient httpClient = HttpClients.custom().
                    setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse response;
            try {
                httpget = new HttpGet(config.getUrl());
                httpget.setConfig(config.getRequestConfig());
//                httpget.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
                httpget.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                //添加cookie 测试// PHPSESSID=v5eh4de63dmetd85ee5d6b62s7;
                //添加cookie 测试
                //search_history_ly_a=title%3d%e5%8f%91%e7%83%a7%2b%2b%2b6%2b%2b%2bAND%7c%7c%7c%26start_year%3d1999%26end_year%3d2015%26nian%3d%26juan%3d%26qi%3d%26xw1%3d%26xw2%3d%26wzlx%3d1%26xkfl1%3d%26jj%3d%26pagenum%3d20%26order_type%3dnian%26order_px%3dDESC
//                httpget.addHeader("Cookie", "PHPSESSID=4ndaoj2283kvnkkrodvshb3r22");
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httpget.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httpget.addHeader(HttpHeaders.HOST, config.getHost());
                }
                response = httpClient.execute(httpget);
                int resStatu = response.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "--状态码" + resStatu);
                if (resStatu == 301 || resStatu == 302) {
                    Header[] hs = response.getHeaders("Location");
                    for (Header h : hs) {
                        System.out.println(h.getName() + "--" + h.getValue());
                    }
                }
                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(response);
                    if (html != null) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static void checkConnection() {
        while (true) {
            if (HttpClientConfig.establishedStatus == 1) {
                break;
            }
            try {
                Thread.currentThread().sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        while (true) {
            if (HttpClientConfig.connectionNums <= HttpClientConfig.CONNECT_LIMIT) {
                break;
            }
            try {
                Thread.currentThread().sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        synchronized (HttpClientConfig.class) {
            HttpClientConfig.connectionNums = HttpClientConfig.connectionNums + 1;
        }
    }

    public static String postRawJsonHtml(CookieStore cookieStore, Map<String, String> map, HttpClientConfig config) {
        System.out.println("httpclient里面的地址" + config.getUrl());
        String html = "";
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(config.getUrl());
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                if (map != null) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                    JSONObject jsonParam = new JSONObject();
                    for (int j = 0; j < nvps.size(); j++) {
                        String param = nvps.get(j).getName();
                        String value = nvps.get(j).getValue();
                        jsonParam.put(param, value);
                    }
                    StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    httppost.setEntity(entity);
                }
                httppost.setConfig(config.getRequestConfig());
                httppost.addHeader("Origin", "https://ieeexplore.ieee.org");
                httppost.setHeader("Content-type", "application/json;charset=UTF-8");
                //返回中文数据
                httppost.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httppost.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httppost.addHeader(HttpHeaders.HOST, config.getHost());
                }
                responce = httpClient.execute(httppost);
                int resStatu = responce.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
                html = HttpClientUtil.parsingHtml(responce);
                System.out.println("返回的数据是" + html);
                //获得相应实体
                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(responce);
                    if (html != null) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {
                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }


    /**
     * 通用的获取html的post方法
     */
    public static String postHtml(CookieStore cookieStore, Map<String, String> map, HttpClientConfig config) {
        System.out.println("httpclient里面的地址" + config.getUrl());
        String html = "";
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(config.getUrl());
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                if (map != null) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                httppost.setEntity(new UrlEncodedFormEntity(nvps, "utf8"));
                httppost.setConfig(config.getRequestConfig());
                httppost.addHeader("Origin", "https://ieeexplore.ieee.org");
//                httppost.addHeader("Cookie","__gads=ID=d242e99c05e19ed2:T=1551100321:S=ALNI_MZwgWjnuwfOkvXzuAYVWYUXiTOI-w; fp=66bf7138e8126ba28d6540b2272ad061; cookieconsent_status=dismiss; s_fid=2DE5F76E2BD7EEB9-30BE03751B2C8CD6; ipCheck=119.164.136.176; JSESSIONID=RE8nVvFJmpL1XTtq8JdaTMKdy33PzyITfc6h-v1BSb72wULyLjAd!-452222108; AMCVS_8E929CC25A1FB2B30A495C97%40AdobeOrg=1; AMCV_8E929CC25A1FB2B30A495C97%40AdobeOrg=1687686476%7CMCIDTS%7C17953%7CMCMID%7C06201714942205603940352095594549609002%7CMCAAMLH-1551749046%7C11%7CMCAAMB-1551749046%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCOPTOUT-1551151446s%7CNONE%7CMCAID%7CNONE%7CvVersion%7C3.0.0; s_cc=true; WLSESSION=203580044.20480.0000; TS011813a0=012f350623740effdf30b4ef87968ab689e75e2322dc4cbc5ccde983b6d76338cb6d9ef171a8f13175b713f5930100afef85dc23555b2f10fdbe2ade8f22c467daa480242466228f5835d6504544a422e62aa0084b; TS01d430e1=012f35062362bb3daf88f71f7e050eeae8685026b0b9a3af0360b0bd81bb170d4388ab7edf6bb7b1ba32ba88a96bda24159f7f90077aee22e3157ef0991e9976c600306ef79b21313bc5b34e98222d0927caf742213f4fb6f2e4d495f84f7c691dc8115e84; TS011813a0_26=014082121d27498325563a9017eadb3fdf6926f3035ba32a70c9603f8209d6da5107ea198d8316b597198a6bccf0f4a748a7ffb453cf02e5d27cd29421cd27be98ee0919dd; utag_main=v_id:016924c8a1bf0013170130db39201207f002b07700bd0$_sn:2$_ss:0$_st:1551146064886$vapi_domain:ieee.org$ses_id:1551144245131%3Bexp-session$_pn:2%3Bexp-session");
                httppost.setHeader("Content-type", "application/json;charset=UTF-8");
                //返回中文数据
//                httppost.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
                httppost.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httppost.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httppost.addHeader(HttpHeaders.HOST, config.getHost());
                }
                responce = httpClient.execute(httppost);
                int resStatu = responce.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
                //获得相应实体
                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(responce);
                    if (html != null) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {
                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }
}
